package com.zz.framework.core.common;

import android.app.Activity;
import android.content.Context;

import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProviders;

/**
 * Copyright © 2020 zanezhao All rights reserved.
 * Created by zanezhao on 2020/3/2 6:04 PM.
 *
 * @author: zanezhao 1820022519@qq.com
 * @version: V1.0
 */
public class ActivityDataBus {
    public static <T extends ActivityShareData> T getData(Context context, Class<T> tClass) {
        return getData(checkContext(context),tClass);
    }

    public static <T extends ActivityShareData> T getData(Activity context, Class<T> tClass) {
        return getData(checkContext(context),tClass);
    }

    public static <T extends ActivityShareData> T getData(FragmentActivity context, Class<T> tClass) {
        return ViewModelProviders.of(context).get(tClass);
    }

    private static FragmentActivity checkContext(Context context) {
        if(context instanceof FragmentActivity) return (FragmentActivity) context;
        throw new IllegalContextException();
    }

    public static class ActivityShareData extends ViewModel {}

    public static class IllegalContextException extends RuntimeException {
        public IllegalContextException() {
            super("ActivityDataBus 需要FragmentActivity作为上下文！");
        }
    }
}
